package com.example.bluejumplib.usb;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;
import android.widget.Toast;

import com.example.bluejumplib.ConnectInterface;

import java.util.HashMap;
import java.util.Iterator;

import felhr.usbservice.UsbService;

public class JumpUsbReceiver extends BroadcastReceiver {

    private static final String TAG = "JumpUsbReceiver";
    public Boolean state = false;
    private ConnectInterface mConnectInterface;

    public void setConnectInterface(ConnectInterface mConnectInterface) {
        this.mConnectInterface = mConnectInterface;
    }

    public void notifyState() {
        if (mConnectInterface != null)
            mConnectInterface.state(state);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        switch (intent.getAction()) {
            //usb设备插入
            case UsbService.ACTION_USB_ATTACHED:
                state = true;
                Log.e(TAG, "Device attached:" + UsbService.ACTION_ADRECEIVER_ATTACHED);
                //向库中发送usb广播消息
                Intent intent1 = new Intent(UsbService.ACTION_ADRECEIVER_ATTACHED);
//                Toast.makeText(context, "ADReceiver USB attached", Toast.LENGTH_SHORT).show();

                context.sendBroadcast(intent1);
                break;
            case UsbService.ACTION_ADRECEIVER_READY:
            case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
                state = true;
                Log.e(TAG, "Device attached:" + UsbService.ACTION_ADRECEIVER_ATTACHED);
//                Toast.makeText(context, "ADReceiver USB Ready", Toast.LENGTH_SHORT).show();
                break;
//                Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
            case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
                state = false;
                Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "ACTION_USB_PERMISSION_NOT_GRANTED: "+state );
                break;
            case UsbService.ACTION_NO_USB: // NO USB CONNECTED
                state = false;
                Log.e(TAG, "No USB connected");
                break;
            case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
                state = false;
                Log.e(TAG, "USB disconnected");
                break;
            case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
                state = false;
                Log.e(TAG, "ACTION_USB_NOT_SUPPORTED");
//                Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
                break;
        }
//        Toast.makeText(context, "USB state"+state, Toast.LENGTH_SHORT).show();
        notifyState();
    }


}
